import { UAParser } from 'ua-parser-js';
import { resolveSrv } from 'node:dns';
import { getLastEventPath } from './getLastEvent';

const {
    device, browser, os
} = UAParser(navigator.userAgent);

/**
 * 获取日志基本信息
 */
export const getLogBase = (): App.BaseLog => {
    return {
        title: document.title,
        url: location.href,
        userAgent: navigator.userAgent,
        browser: `${browser.name} ${browser.version}`,
        device: `${device.model} ${device.vendor}`,
        os: `${os.name} ${os.version}`
    }
}

export const filterTopLevelNode = (ele: Window | Document | HTMLElement) => {
    /**
     * 过滤window、document和html
     */
    return ele !== window && ele !== document && ele !== document.documentElement;
}

export const getSelector = (ele?: Element) => {
    const path = getLastEventPath();
    if (Array.isArray(path)) {
        return path.reverse().filter(filterTopLevelNode).map(getEleSelector).join(' ');
    } else if (ele) {
        return getEleSelector(ele);
    }
};


export const getEleSelector = (ele: Element) => {
    let selector;
    if (ele.id) {
        selector = `#${ele.id}`;
    } else if (ele.className) {
        selector = '.' + ele.className.split(' ').filter(item => !!item).join('.');
    } else {
        selector= ele.nodeName.toLowerCase();
    }
    return selector;
}


/**
 * 格式化堆栈信息
 * @param stack
 */
export const formatStack = (stack: string) => {
    // -------- 原 stack：
    // TypeError: Cannot set properties of undefined (setting 'error')
    //   at errorClick (http://localhost:8080/:23:30)
    //   at HTMLInputElement.onclick (http://localhost:8080/:11:70)
    // -------- 格式化为：
    //   errorClick (http://localhost:8080/:23:30)
    //   HTMLInputElement.onclick (http://localhost:8080/:11:70)
    return stack
        .split("\n")
        .slice(1)
        .map(item => item.replace(/^\s+at\s+/g, ""))
        .join("\n");
}
